import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, 
  Button, 
  Modal, 
  Form, 
  DatePicker, 
  Input, 
  List, 
  Checkbox, 
  Typography, 
  Space, 
  Tag, 
  Popconfirm, 
  message, 
  Row, 
  Col, 
  Spin,
  Empty,
  Tooltip
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  CalendarOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  BookOutlined,
  RobotOutlined,
  HolderOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { studyService, aiService } from '../services/api';
// 移除拖拽相关导入
// 移除拖拽相关导入
import './StudyPlan.css';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

// 设置dayjs为中文
dayjs.locale('zh-cn');

// 可拖拽的卡片组件
interface StudyCardProps {
  card: StudyCard;
  inputValues: {[key: string]: string};
  onEdit: (card: StudyCard) => void;
  onDelete: (id: string) => void;
  onToggleTodo: (cardId: string, todoId: string) => void;
  onDeleteTodo: (cardId: string, todoId: string) => void;
  onAddTodo: (cardId: string, text: string) => void;
  onInputChange: (cardId: string, value: string) => void;
  onInputPressEnter: (cardId: string, value: string) => void;
}

const StudyCard: React.FC<StudyCardProps> = ({
  card,
  inputValues,
  onEdit,
  onDelete,
  onToggleTodo,
  onDeleteTodo,
  onAddTodo,
  onInputChange,
  onInputPressEnter,
}) => {

  const getDateRangeDisplay = (startDate: string, endDate: string) => {
    const start = dayjs(startDate);
    const end = dayjs(endDate);
    const today = dayjs();
    
    // 计算相对日期
    const getRelativeDate = (date: string) => {
      const targetDate = dayjs(date);
      const diffDays = targetDate.diff(today, 'day');
      
      if (diffDays === 0) {
        return '今天';
      } else if (diffDays === 1) {
        return '明天';
      } else if (diffDays === -1) {
        return '昨天';
      } else if (diffDays > 0) {
        return `${diffDays}天后`;
      } else {
        return `${Math.abs(diffDays)}天前`;
      }
    };
    
    if (start.isSame(end, 'day')) {
      return `${start.format('MM月DD日')} (${getRelativeDate(startDate)})`;
    }
    
    if (start.isSame(end, 'month')) {
      return `${start.format('MM月DD日')} - ${end.format('DD日')}`;
    }
    
    return `${start.format('MM月DD日')} - ${end.format('MM月DD日')}`;
  };

  return (
    <Card
      className="study-card"
      hoverable
    >

        {/* 卡片操作按钮 */}
        <div className="card-actions">
          <Tooltip title="编辑">
            <Button 
              className="card-action-btn"
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => onEdit(card)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个学习计划吗？"
            onConfirm={() => onDelete(card.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              className="card-action-btn danger"
              type="text" 
              danger 
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </div>

        {/* 卡片内容 */}
        <div className="card-content">
          {/* 卡片标题 */}
          <div className="card-title">
            {card.title}
          </div>

          {/* 卡片描述 */}
          <div className="card-description">
            {card.description}
          </div>

          {/* 日期信息 */}
          <div className="card-date-info">
            <CalendarOutlined className="card-date-icon" />
            <span className="card-date-text">
              {getDateRangeDisplay(card.startDate, card.endDate)}
            </span>
          </div>

          {/* 待办事项 */}
          <div className="card-todos">
            <div className="card-todos-header">
              <span className="card-todos-title">学习任务</span>
              <span className="card-todos-count">
                {(card.todos || []).filter(todo => !todo.completed).length} 待完成
              </span>
            </div>
            
            {(card.todos || []).length === 0 ? (
              <div className="empty-todos">暂无任务</div>
            ) : (
              <div className="todos-list">
                {(card.todos || []).map(todo => (
                  <div key={todo.id} className="todo-item">
                    <Checkbox
                      className="todo-checkbox"
                      checked={todo.completed}
                      onChange={() => onToggleTodo(card.id, todo.id)}
                    />
                    <span 
                      className={`todo-text ${todo.completed ? 'completed' : ''}`}
                    >
                      {todo.text}
                    </span>
                    <Button
                      className="todo-delete-btn"
                      type="text"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => onDeleteTodo(card.id, todo.id)}
                    />
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 添加待办事项 */}
          <div className="add-todo-input">
            <Input
              placeholder="添加新的学习任务..."
              value={inputValues[card.id] || ''}
              onChange={(e) => onInputChange(card.id, e.target.value)}
              onPressEnter={(e) => {
                const value = (inputValues[card.id] || '').trim();
                if (value) {
                  onInputPressEnter(card.id, value);
                }
              }}
            />
          </div>
        </div>
    </Card>
  );
};

interface TodoItem {
  id: string;
  text: string;
  completed: boolean;
  createdAt: string;
}

interface StudyCard {
  id: string;
  title: string;
  description: string;
  startDate: string;
  endDate: string;
  todos: TodoItem[];
  createdAt: string;
  updatedAt: string;
}

const StudyPlan: React.FC = () => {
  const [cards, setCards] = useState<StudyCard[]>([]);
  const [loading, setLoading] = useState(true);
  const [pageReady, setPageReady] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCard, setEditingCard] = useState<StudyCard | null>(null);
  const [form] = Form.useForm();
  const [inputValues, setInputValues] = useState<{[key: string]: string}>({});
  const [aiModalVisible, setAiModalVisible] = useState(false);
  const [aiInputValue, setAiInputValue] = useState('');
  const [aiGenerating, setAiGenerating] = useState(false);
  
  // 移除拖拽相关状态
  
  // 移除拖拽相关函数

  // 移除拖拽相关函数

  // 移除拖拽相关函数

  // 移除窗口大小变化处理

  // 页面初始化
  useEffect(() => {
    const initializePage = async () => {
      setLoading(true);
      try {
        // 加载学习计划数据
        const response = await studyService.getPlans();
        console.log('学习计划API响应:', response);
        
        if (response && (response as any).success) {
          const plans = (response as any).plans || [];
          
          // 为每个计划加载任务数据
          const plansWithTasks = await Promise.all(
            plans.map(async (plan: any) => {
              try {
                const tasksResponse = await studyService.getTasks(plan.id);
                console.log(`计划${plan.id}的任务API响应:`, tasksResponse);
                
                if (tasksResponse && (tasksResponse as any).success) {
                  const tasks = (tasksResponse as any).tasks || [];
                  return {
                    ...plan,
                    startDate: plan.start_date,
                    endDate: plan.end_date,
                    todos: tasks.map((task: any) => ({
                      id: task.id.toString(),
                      text: task.title,
                      completed: task.is_completed === 1,
                      createdAt: task.created_at
                    }))
                  };
                } else {
                  return {
                    ...plan,
                    startDate: plan.start_date,
                    endDate: plan.end_date,
                    todos: []
                  };
                }
              } catch (error) {
                console.error(`加载计划${plan.id}的任务失败:`, error);
                return {
                  ...plan,
                  startDate: plan.start_date,
                  endDate: plan.end_date,
                  todos: []
                };
              }
            })
          );
          
          setCards(plansWithTasks);
        } else {
          console.warn('API响应格式异常:', response);
          setCards([]);
        }
      } catch (error: any) {
        console.error('加载学习计划失败:', error);
        console.error('错误详情:', error.response?.data || error.message);
        
        // 如果是认证错误，显示登录提示
        if (error.response?.status === 401) {
          message.error('请先登录后再使用学习规划功能');
        } else {
          message.error('加载学习计划失败，请检查网络连接');
        }
        
        // 使用模拟数据（仅用于开发测试）
        console.log('使用模拟数据');
        setCards([
          {
            id: 'demo-1',
            title: '数学复习计划',
            description: '准备期末考试，重点复习微积分和线性代数',
            startDate: dayjs().format('YYYY-MM-DD'),
            endDate: dayjs().add(14, 'day').format('YYYY-MM-DD'),
            todos: [
              {
                id: 'todo-1',
                text: '完成微积分练习题',
                completed: false,
                createdAt: new Date().toISOString()
              },
              {
                id: 'todo-2',
                text: '复习线性代数概念',
                completed: true,
                createdAt: new Date().toISOString()
              }
            ],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ]);
      } finally {
        setLoading(false);
        setPageReady(true);
      }
    };

    initializePage();
  }, []);

  // 格式化日期显示
  const formatDateDisplay = (date: string) => {
    const targetDate = dayjs(date);
    const today = dayjs();
    const diffDays = targetDate.diff(today, 'day');

    if (diffDays === 0) {
      return '今天';
    } else if (diffDays === 1) {
      return '明天';
    } else if (diffDays === -1) {
      return '昨天';
    } else if (diffDays > 0) {
      return `${diffDays}天后`;
    } else {
      return `${Math.abs(diffDays)}天前`;
    }
  };


  // 创建新卡片
  const handleCreateCard = () => {
    setEditingCard(null);
    form.resetFields();
    setModalVisible(true);
  };

  // AI生成学习计划
  const handleAiGenerate = async () => {
    if (!aiInputValue.trim()) {
      message.warning('请输入学习需求');
      return;
    }

    setAiGenerating(true);
    try {
      // 构建AI提示词
      const currentDate = dayjs().format('YYYY-MM-DD');
      
      // 从用户输入中提取时间信息
      // 先尝试匹配阿拉伯数字
      let timeMatch = aiInputValue.match(/(\d+)\s*天|(\d+)\s*日|(\d+)\s*周|(\d+)\s*月|(\d+)\s*个月/);
      let studyDays = 30; // 默认30天
      
      if (timeMatch) {
        console.log('阿拉伯数字时间匹配结果:', timeMatch);
        if (timeMatch[1]) {
          studyDays = parseInt(timeMatch[1]); // 天
          console.log('提取到天数:', studyDays);
        } else if (timeMatch[2]) {
          studyDays = parseInt(timeMatch[2]); // 日
          console.log('提取到日数:', studyDays);
        } else if (timeMatch[3]) {
          studyDays = parseInt(timeMatch[3]) * 7; // 周转天
          console.log('提取到周数:', studyDays);
        } else if (timeMatch[4]) {
          studyDays = parseInt(timeMatch[4]) * 30; // 月转天
          console.log('提取到月数:', studyDays);
        } else if (timeMatch[5]) {
          studyDays = parseInt(timeMatch[5]) * 30; // 个月转天
          console.log('提取到月数:', studyDays);
        }
      } else {
        // 尝试匹配中文数字
        const chineseTimeMatch = aiInputValue.match(/([一二三四五六七八九十]+)\s*天|([一二三四五六七八九十]+)\s*日|([一二三四五六七八九十]+)\s*周|([一二三四五六七八九十]+)\s*月|([一二三四五六七八九十]+)\s*个月/);
        if (chineseTimeMatch) {
          console.log('中文数字时间匹配结果:', chineseTimeMatch);
          const chineseToNumber = (chinese: string) => {
            const map: { [key: string]: number } = {
              '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
            };
            return map[chinese] || 0;
          };
          
          if (chineseTimeMatch[1]) {
            studyDays = chineseToNumber(chineseTimeMatch[1]); // 天
            console.log('提取到中文天数:', studyDays);
          } else if (chineseTimeMatch[2]) {
            studyDays = chineseToNumber(chineseTimeMatch[2]); // 日
            console.log('提取到中文日数:', studyDays);
          } else if (chineseTimeMatch[3]) {
            studyDays = chineseToNumber(chineseTimeMatch[3]) * 7; // 周转天
            console.log('提取到中文周数:', studyDays);
          } else if (chineseTimeMatch[4]) {
            studyDays = chineseToNumber(chineseTimeMatch[4]) * 30; // 月转天
            console.log('提取到中文月数:', studyDays);
          } else if (chineseTimeMatch[5]) {
            studyDays = chineseToNumber(chineseTimeMatch[5]) * 30; // 个月转天
            console.log('提取到中文月数:', studyDays);
          }
        } else {
          console.log('未匹配到时间信息，使用默认30天');
        }
      }
      
      console.log('最终学习天数:', studyDays);
      
      const endDate = dayjs().add(studyDays, 'day').format('YYYY-MM-DD');
      
      const prompt = `生成学习计划JSON

用户需求：${aiInputValue}
学习时间：${studyDays}天

请生成一个完整的学习计划JSON，包含以下字段：
- title: 学习计划标题（10-20字，体现${studyDays}天时间）
- description: 计划描述（50-100字，说明${studyDays}天的学习安排）
- startDate: "${currentDate}"
- endDate: "${endDate}"
- todos: 3-5个学习任务数组（适合${studyDays}天学习）

要求：
1. 必须返回完整的JSON格式
2. 不要添加任何其他文字
3. JSON必须是有效的格式
4. 学习任务要适合${studyDays}天的学习时间

示例格式：
{
  "title": "${studyDays}天Java编程学习计划",
  "description": "在${studyDays}天内掌握Java核心知识的学习安排",
  "startDate": "${currentDate}",
  "endDate": "${endDate}",
  "todos": [
    {"text": "学习Java基础语法"},
    {"text": "掌握面向对象编程"},
    {"text": "完成项目实战"}
  ]
}`;

      const response = await aiService.generateTitle(prompt) as any;
      
      if (response.success && response.data) {
        try {
          // 解析AI返回的JSON
          const aiResponse = response.data.title || response.data.content || response.data;
          console.log('AI原始响应:', aiResponse);
          
          // 尝试提取JSON部分
          let jsonStr = aiResponse;
          
          // 如果响应包含代码块，提取其中的JSON
          const jsonMatch = aiResponse.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
          if (jsonMatch) {
            jsonStr = jsonMatch[1];
          } else {
            // 如果没有代码块，尝试找到第一个完整的JSON对象
            const jsonStart = aiResponse.indexOf('{');
            const jsonEnd = aiResponse.lastIndexOf('}');
            if (jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart) {
              jsonStr = aiResponse.substring(jsonStart, jsonEnd + 1);
            }
          }
          
          console.log('提取的JSON字符串:', jsonStr);
          
          // 尝试修复常见的JSON格式问题
          try {
            // 检查JSON是否完整
            if (!jsonStr.includes('"title"') || !jsonStr.includes('"description"')) {
              throw new Error('JSON格式不完整');
            }
            
            // 尝试修复不完整的JSON
            if (jsonStr.includes('"title":') && !jsonStr.includes('"title": "')) {
              jsonStr = jsonStr.replace(/"title":\s*([^,}]+)/, '"title": "$1"');
            }
            if (jsonStr.includes('"description":') && !jsonStr.includes('"description": "')) {
              jsonStr = jsonStr.replace(/"description":\s*([^,}]+)/, '"description": "$1"');
            }
            
            // 如果JSON仍然不完整，尝试构建完整的JSON
            if (!jsonStr.includes('"todos"') || !jsonStr.includes('"startDate"') || !jsonStr.includes('"endDate"')) {
              console.log('JSON不完整，尝试构建完整JSON...');
              
              // 提取已有的字段
              const titleMatch = jsonStr.match(/"title":\s*"([^"]*)"/);
              const descMatch = jsonStr.match(/"description":\s*"([^"]*)"/);
              
              const title = titleMatch ? titleMatch[1] : `基于"${aiInputValue}"的学习计划`;
              const description = descMatch ? descMatch[1] : `根据您的需求"${aiInputValue}"制定的个性化学习计划`;
              
              // 构建完整的JSON
              jsonStr = JSON.stringify({
                title: title,
                description: description,
                startDate: currentDate,
                endDate: endDate,
                todos: [
                  { text: '学习基础理论' },
                  { text: '完成实践练习' },
                  { text: '进行项目应用' },
                  { text: '总结和复习' }
                ]
              });
              
              console.log('构建的完整JSON:', jsonStr);
            }
            
            const planData = JSON.parse(jsonStr);
            
            // 验证必要字段
            if (!planData.title || !planData.description || !planData.todos) {
              throw new Error('JSON缺少必要字段');
            }
            
            console.log('成功解析的JSON数据:', planData);
            
            // 创建学习计划
            const planDataToSave = {
              title: planData.title,
              description: planData.description,
              start_date: planData.startDate,
              end_date: planData.endDate
            };

            const createResponse = await studyService.createPlan(planDataToSave);
            
            if (createResponse && (createResponse as any).success) {
            const planId = (createResponse as any).plan_id.toString();
            
            // 创建学习计划卡片（先不包含任务）
            const newCard: StudyCard = {
              id: planId,
              title: planData.title,
              description: planData.description,
              startDate: planData.startDate,
              endDate: planData.endDate,
              todos: [],
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString()
            };

            // 先添加卡片到界面
            setCards(prev => [newCard, ...prev]);

            // 然后创建任务并保存到数据库
            const savedTodos: TodoItem[] = [];
            for (const todo of planData.todos) {
              try {
                const taskData = {
                  title: todo.text,
                  description: '',
                  priority: 'medium'
                };
                
                const taskResponse = await studyService.createTask(planId, taskData);
                if (taskResponse && (taskResponse as any).success) {
                  savedTodos.push({
                    id: (taskResponse as any).task_id.toString(),
                    text: todo.text,
                    completed: false,
                    createdAt: new Date().toISOString()
                  });
                }
              } catch (taskError) {
                console.error('创建任务失败:', taskError);
                // 即使任务创建失败，也添加到本地状态
                savedTodos.push({
                  id: `local-todo-${Date.now()}-${Math.random()}`,
                  text: todo.text,
                  completed: false,
                  createdAt: new Date().toISOString()
                });
              }
            }

            // 更新卡片中的任务
            setCards(prev => prev.map(card => 
              card.id === planId 
                ? { ...card, todos: savedTodos }
                : card
            ));

              message.success('AI学习计划生成成功！');
              setAiModalVisible(false);
              setAiInputValue('');
            } else {
              throw new Error('创建学习计划失败');
            }
          } catch (jsonParseError) {
            console.error('JSON解析失败:', jsonParseError);
            throw new Error('JSON格式错误，将使用备选方案');
          }
        } catch (parseError) {
          console.error('解析AI响应失败:', parseError);
          console.log('尝试使用备选方案...');
          
          // 备选方案：使用简单的文本解析
          try {
            const aiResponse = response.data.title || response.data.content || response.data;
            const lines = aiResponse.split('\n').filter((line: string) => line.trim());
            
            // 尝试从文本中提取信息
            const title = lines.find((line: string) => line.includes('标题') || line.includes('计划'))?.replace(/.*[:：]\s*/, '') || `基于"${aiInputValue}"的学习计划`;
            const description = lines.find((line: string) => line.includes('描述') || line.includes('内容'))?.replace(/.*[:：]\s*/, '') || `根据您的需求"${aiInputValue}"制定的个性化学习计划`;
            
            // 从用户输入中提取时间信息（备选方案）
            let timeMatch = aiInputValue.match(/(\d+)\s*天|(\d+)\s*日|(\d+)\s*周|(\d+)\s*月|(\d+)\s*个月/);
            let studyDays = 30; // 默认30天
            
            if (timeMatch) {
              if (timeMatch[1]) studyDays = parseInt(timeMatch[1]); // 天
              else if (timeMatch[2]) studyDays = parseInt(timeMatch[2]); // 日
              else if (timeMatch[3]) studyDays = parseInt(timeMatch[3]) * 7; // 周转天
              else if (timeMatch[4]) studyDays = parseInt(timeMatch[4]) * 30; // 月转天
              else if (timeMatch[5]) studyDays = parseInt(timeMatch[5]) * 30; // 个月转天
            } else {
              // 尝试匹配中文数字
              const chineseTimeMatch = aiInputValue.match(/([一二三四五六七八九十]+)\s*天|([一二三四五六七八九十]+)\s*日|([一二三四五六七八九十]+)\s*周|([一二三四五六七八九十]+)\s*月|([一二三四五六七八九十]+)\s*个月/);
              if (chineseTimeMatch) {
                const chineseToNumber = (chinese: string) => {
                  const map: { [key: string]: number } = {
                    '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
                  };
                  return map[chinese] || 0;
                };
                
                if (chineseTimeMatch[1]) studyDays = chineseToNumber(chineseTimeMatch[1]); // 天
                else if (chineseTimeMatch[2]) studyDays = chineseToNumber(chineseTimeMatch[2]); // 日
                else if (chineseTimeMatch[3]) studyDays = chineseToNumber(chineseTimeMatch[3]) * 7; // 周转天
                else if (chineseTimeMatch[4]) studyDays = chineseToNumber(chineseTimeMatch[4]) * 30; // 月转天
                else if (chineseTimeMatch[5]) studyDays = chineseToNumber(chineseTimeMatch[5]) * 30; // 个月转天
              }
            }
            
            const startDate = dayjs().format('YYYY-MM-DD');
            const endDate = dayjs().add(studyDays, 'day').format('YYYY-MM-DD');
            
            // 提取任务（查找包含"任务"或数字的行）
            let todos = lines
              .filter((line: string) => /^\d+[\.、]|任务|学习|练习|复习/.test(line.trim()))
              .map((line: string, index: number) => ({
                text: line.replace(/^\d+[\.、]\s*/, '').trim()
              }))
              .slice(0, 5); // 最多5个任务
            
            // 如果没有找到任务，根据用户输入和学习天数生成个性化任务
            if (todos.length === 0) {
              const userInput = aiInputValue.toLowerCase();
              const taskCount = Math.min(Math.max(3, Math.floor(studyDays / 7)), 7); // 根据学习天数调整任务数量
              
              if (userInput.includes('python') || userInput.includes('编程')) {
                todos = [
                  { text: '学习Python基础语法' },
                  { text: '掌握数据结构与算法' },
                  { text: '完成实际项目练习' }
                ];
                if (studyDays >= 14) todos.push({ text: '学习框架和库的使用' });
                if (studyDays >= 21) todos.push({ text: '完成综合项目实战' });
                if (studyDays >= 30) todos.push({ text: '学习高级特性和优化' });
              } else if (userInput.includes('react') || userInput.includes('前端')) {
                todos = [
                  { text: '学习React基础概念' },
                  { text: '掌握组件开发' },
                  { text: '学习状态管理' }
                ];
                if (studyDays >= 14) todos.push({ text: '完成项目实战' });
                if (studyDays >= 21) todos.push({ text: '学习路由和部署' });
              } else if (userInput.includes('机器学习') || userInput.includes('ai')) {
                todos = [
                  { text: '学习数学基础' },
                  { text: '掌握机器学习算法' },
                  { text: '完成数据预处理' }
                ];
                if (studyDays >= 14) todos.push({ text: '构建预测模型' });
                if (studyDays >= 21) todos.push({ text: '模型优化和评估' });
              } else {
                todos = [
                  { text: '学习基础理论' },
                  { text: '完成实践练习' }
                ];
                if (studyDays >= 7) todos.push({ text: '进行项目应用' });
                if (studyDays >= 14) todos.push({ text: '总结和复习' });
              }
              
              // 确保任务数量不超过计算的数量
              todos = todos.slice(0, taskCount);
            }
            
            const planData = {
              title,
              description,
              startDate,
              endDate,
              todos
            };
            
            console.log('使用备选方案生成的数据:', planData);
            
            // 继续执行创建计划逻辑
            const planDataToSave = {
              title: planData.title,
              description: planData.description,
              start_date: planData.startDate,
              end_date: planData.endDate
            };

            const createResponse = await studyService.createPlan(planDataToSave);
            
            if (createResponse && (createResponse as any).success) {
              const planId = (createResponse as any).plan_id.toString();
              
              // 创建学习计划卡片（先不包含任务）
              const newCard: StudyCard = {
                id: planId,
                title: planData.title,
                description: planData.description,
                startDate: planData.startDate,
                endDate: planData.endDate,
                todos: [],
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
              };

              // 先添加卡片到界面
              setCards(prev => [newCard, ...prev]);

              // 然后创建任务并保存到数据库
              const savedTodos: TodoItem[] = [];
              for (const todo of planData.todos) {
                try {
                  const taskData = {
                    title: todo.text,
                    description: '',
                    priority: 'medium'
                  };
                  
                  const taskResponse = await studyService.createTask(planId, taskData);
                  if (taskResponse && (taskResponse as any).success) {
                    savedTodos.push({
                      id: (taskResponse as any).task_id.toString(),
                      text: todo.text,
                      completed: false,
                      createdAt: new Date().toISOString()
                    });
                  }
                } catch (taskError) {
                  console.error('创建任务失败:', taskError);
                  // 即使任务创建失败，也添加到本地状态
                  savedTodos.push({
                    id: `local-todo-${Date.now()}-${Math.random()}`,
                    text: todo.text,
                    completed: false,
                    createdAt: new Date().toISOString()
                  });
                }
              }

              // 更新卡片中的任务
              setCards(prev => prev.map(card => 
                card.id === planId 
                  ? { ...card, todos: savedTodos }
                  : card
              ));

              message.success('AI学习计划生成成功！（使用备选方案）');
              setAiModalVisible(false);
              setAiInputValue('');
            } else {
              throw new Error('创建学习计划失败');
            }
          } catch (fallbackError) {
            console.error('备选方案也失败了:', fallbackError);
            message.error('AI响应格式错误，请重试或手动创建学习计划');
          }
        }
      } else {
        throw new Error('AI生成失败');
      }
    } catch (error: any) {
      console.error('AI生成学习计划失败:', error);
      message.error('AI生成学习计划失败，请重试');
    } finally {
      setAiGenerating(false);
    }
  };

  // 编辑卡片
  const handleEditCard = (card: StudyCard) => {
    setEditingCard(card);
    form.setFieldsValue({
      title: card.title,
      description: card.description,
      dateRange: [dayjs(card.startDate), dayjs(card.endDate)]
    });
    setModalVisible(true);
  };

  // 删除卡片
  const handleDeleteCard = async (cardId: string) => {
    try {
      const response = await studyService.deletePlan(cardId);
      console.log('删除计划API响应:', response);
      
      if (response && (response as any).success) {
        setCards(prev => prev.filter(card => card.id !== cardId));
        message.success('学习计划已删除');
      } else {
        throw new Error((response as any)?.message || '删除失败');
      }
    } catch (error: any) {
      console.error('删除学习计划失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      message.error('删除学习计划失败');
    }
  };

  // 保存卡片
  const handleSaveCard = async (values: any) => {
    const { title, description, dateRange } = values;
    const [startDate, endDate] = dateRange;

    // 将 planData 定义在 try-catch 块外部，确保在 catch 块中也能访问
    const planData = {
      title,
      description,
      start_date: startDate.format('YYYY-MM-DD'),
      end_date: endDate.format('YYYY-MM-DD')
    };

    try {
      if (editingCard) {
        // 更新现有计划
        const response = await studyService.updatePlan(editingCard.id, planData);
        console.log('更新计划API响应:', response);
        
        if (response && (response as any).success) {
          message.success('学习计划已更新');
          
          // 更新本地状态
          setCards(prev => prev.map(card => 
            card.id === editingCard.id 
              ? { 
                  ...card, 
                  title: planData.title,
                  description: planData.description,
                  startDate: planData.start_date,
                  endDate: planData.end_date,
                  updatedAt: new Date().toISOString() 
                }
              : card
          ));
        } else {
          throw new Error((response as any)?.message || '更新失败');
        }
      } else {
        // 创建新计划
        const response = await studyService.createPlan(planData);
        console.log('创建计划API响应:', response);
        
        if (response && (response as any).success) {
          message.success('学习计划已创建');
          
          // 添加到本地状态
          const newCard: StudyCard = {
            id: (response as any).plan_id.toString(),
            title,
            description,
            startDate: planData.start_date,
            endDate: planData.end_date,
            todos: [],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          };
          setCards(prev => [newCard, ...prev]);
        } else {
          throw new Error((response as any)?.message || '创建失败');
        }
      }
    } catch (error: any) {
      console.error('保存学习计划失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用学习规划功能');
      } else {
        message.error('保存学习计划失败，已保存到本地');
        
        // 使用本地存储作为备用方案
        if (editingCard) {
          // 更新本地状态
          setCards(prev => prev.map(card => 
            card.id === editingCard.id 
              ? { 
                  ...card, 
                  title: planData.title,
                  description: planData.description,
                  startDate: planData.start_date,
                  endDate: planData.end_date,
                  updatedAt: new Date().toISOString() 
                }
              : card
          ));
          message.success('学习计划已更新（本地）');
        } else {
          // 创建新计划
          const newCard: StudyCard = {
            id: `local-${Date.now()}`,
            title,
            description,
            startDate: planData.start_date,
            endDate: planData.end_date,
            todos: [],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          };
          setCards(prev => [newCard, ...prev]);
          message.success('学习计划已创建（本地）');
        }
      }
    }

    setModalVisible(false);
    setEditingCard(null);
    form.resetFields();
  };

  // 添加待办事项
  const handleAddTodo = async (cardId: string, text: string) => {
    if (!text.trim()) return;

    try {
      const taskData = {
        title: text.trim(),
        description: '',
        priority: 'medium'
      };

      const response = await studyService.createTask(cardId, taskData);
      console.log('创建任务API响应:', response);
      
      if (response && (response as any).success) {
        const newTodo: TodoItem = {
          id: (response as any).task_id.toString(),
          text: text.trim(),
          completed: false,
          createdAt: new Date().toISOString()
        };

        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? { ...card, todos: [...(card.todos || []), newTodo] }
            : card
        ));
      } else {
        throw new Error((response as any)?.message || '创建任务失败');
      }
    } catch (error: any) {
      console.error('添加学习任务失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用学习规划功能');
      } else {
        message.error('添加学习任务失败，已保存到本地');
        
        // 使用本地存储作为备用方案
        const newTodo: TodoItem = {
          id: `local-todo-${Date.now()}`,
          text: text.trim(),
          completed: false,
          createdAt: new Date().toISOString()
        };

        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? { ...card, todos: [...(card.todos || []), newTodo] }
            : card
        ));
        message.success('学习任务已添加（本地）');
      }
    }
  };

  // 切换待办事项状态
  const handleToggleTodo = async (cardId: string, todoId: string) => {
    try {
      const card = cards.find(c => c.id === cardId);
      const todo = card?.todos.find(t => t.id === todoId);
      if (!todo) return;

      const response = await studyService.updateTask(todoId, {
        is_completed: !todo.completed
      });
      console.log('更新任务API响应:', response);

      if (response && (response as any).success) {
        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? {
                ...card,
                todos: (card.todos || []).map(todo => 
                  todo.id === todoId ? { ...todo, completed: !todo.completed } : todo
                )
              }
            : card
        ));
      } else {
        throw new Error((response as any)?.message || '更新任务失败');
      }
    } catch (error: any) {
      console.error('更新学习任务失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用学习规划功能');
      } else {
        message.error('更新学习任务失败，已保存到本地');
        
        // 使用本地存储作为备用方案
        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? {
                ...card,
                todos: (card.todos || []).map(todo => 
                  todo.id === todoId ? { ...todo, completed: !todo.completed } : todo
                )
              }
            : card
        ));
        message.success('学习任务已更新（本地）');
      }
    }
  };

  // 删除待办事项
  const handleDeleteTodo = async (cardId: string, todoId: string) => {
    try {
      const response = await studyService.deleteTask(todoId);
      console.log('删除任务API响应:', response);
      
      if (response && (response as any).success) {
        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? { ...card, todos: (card.todos || []).filter(todo => todo.id !== todoId) }
            : card
        ));
      } else {
        throw new Error((response as any)?.message || '删除任务失败');
      }
    } catch (error: any) {
      console.error('删除学习任务失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用学习规划功能');
      } else {
        message.error('删除学习任务失败，已从本地删除');
        
        // 使用本地存储作为备用方案
        setCards(prev => prev.map(card => 
          card.id === cardId 
            ? { ...card, todos: (card.todos || []).filter(todo => todo.id !== todoId) }
            : card
        ));
        message.success('学习任务已删除（本地）');
      }
    }
  };

  // 如果页面未准备好，显示加载状态
  if (!pageReady) {
    return (
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        height: 'calc(100vh - 160px)',
        background: 'white',
        color: '#2c3e50',
        margin: '-24px -16px'
      }}>
        <Spin size="large" />
        <div style={{ marginTop: '20px', fontSize: '16px' }}>
          正在加载学习规划...
        </div>
      </div>
    );
  }

  return (
    <div style={{ 
      height: '100%',
      background: 'transparent',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      padding: '20px',
      overflow: 'auto'
    }}>
      {/* 卡片列表 - 居中显示 */}
      {cards.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '60px 20px' }}>
          {/* 页面标题 - 只在无卡片时显示 */}
          <div style={{ marginBottom: '30px' }}>
            <Title level={2} style={{ color: '#2c3e50', marginBottom: '10px' }}>
              <BookOutlined style={{ marginRight: '10px' }} />
              学习规划
            </Title>
            <Text style={{ color: '#666', fontSize: '16px' }}>
              制定您的学习计划，合理安排时间，提高学习效率
            </Text>
          </div>
          
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="还没有学习计划，点击下方按钮创建第一个计划吧！"
          />
          <div style={{ marginTop: '30px' }}>
            <Button
              type="primary"
              size="large"
              icon={<PlusOutlined />}
              onClick={handleCreateCard}
              style={{
                background: '#1890ff',
                border: 'none',
                borderRadius: '8px',
                height: '50px',
                padding: '0 30px',
                fontSize: '16px',
                fontWeight: 'bold'
              }}
            >
              创建学习计划
            </Button>
          </div>
        </div>
      ) : (
        <div className="study-plan-container">
          <Row gutter={[32, 32]} justify="center" style={{ margin: 0 }}>
            {cards.map(card => (
              <Col key={card.id} xs={24} sm={12} md={8} lg={6} xl={4} style={{ minWidth: '320px' }}>
                <StudyCard
                  card={card}
                  inputValues={inputValues}
                  onEdit={handleEditCard}
                  onDelete={handleDeleteCard}
                  onToggleTodo={handleToggleTodo}
                  onDeleteTodo={handleDeleteTodo}
                  onAddTodo={handleAddTodo}
                  onInputChange={(cardId, value) => {
                    setInputValues(prev => ({
                      ...prev,
                      [cardId]: value
                    }));
                  }}
                  onInputPressEnter={(cardId, value) => {
                    handleAddTodo(cardId, value);
                    setInputValues(prev => ({
                      ...prev,
                      [cardId]: ''
                    }));
                  }}
                />
              </Col>
            ))}
          </Row>
        </div>
      )}

      {/* 右下角浮动按钮组 - 仅当有卡片时显示 */}
      {cards.length > 0 && (
          <div style={{
            position: 'fixed',
            bottom: '30px',
            right: '30px',
            display: 'flex',
            flexDirection: 'column',
            gap: '15px',
            zIndex: 1000
          }}>
            {/* AI生成按钮 */}
            <Tooltip title="AI智能生成学习计划">
              <Button
                type="primary"
                shape="circle"
                size="large"
                icon={<RobotOutlined />}
                onClick={() => setAiModalVisible(true)}
                style={{
                  width: '60px',
                  height: '60px',
                  background: '#52c41a',
                  border: 'none',
                  borderRadius: '50%',
                  boxShadow: '0 4px 12px rgba(82, 196, 26, 0.4)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              />
            </Tooltip>
            
            {/* 手动创建按钮 */}
            <Tooltip title="手动创建学习计划">
              <Button
                type="primary"
                shape="circle"
                size="large"
                icon={<PlusOutlined />}
                onClick={handleCreateCard}
                style={{
                  width: '60px',
                  height: '60px',
                  background: '#1890ff',
                  border: 'none',
                  borderRadius: '50%',
                  boxShadow: '0 4px 12px rgba(24, 144, 255, 0.4)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              />
            </Tooltip>
          </div>
      )}

      {/* 创建/编辑卡片模态框 */}
      <Modal
          title={editingCard ? '编辑学习计划' : '创建学习计划'}
          open={modalVisible}
          onCancel={() => {
            setModalVisible(false);
            setEditingCard(null);
            form.resetFields();
          }}
          onOk={() => form.submit()}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSaveCard}
          >
            <Form.Item
              name="title"
              label="计划标题"
              rules={[{ required: true, message: '请输入计划标题' }]}
            >
              <Input placeholder="例如：数学复习计划" />
            </Form.Item>

            <Form.Item
              name="description"
              label="计划描述"
              rules={[{ required: true, message: '请输入计划描述' }]}
            >
              <TextArea 
                placeholder="描述这个学习计划的具体内容..."
                rows={3}
              />
            </Form.Item>

            <Form.Item
              name="dateRange"
              label="学习时间"
              rules={[{ required: true, message: '请选择学习时间' }]}
            >
              <RangePicker
                style={{ width: '100%' }}
                placeholder={['开始日期', '结束日期']}
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Form>
      </Modal>

      {/* AI生成学习计划模态框 */}
      <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <RobotOutlined style={{ color: '#52c41a' }} />
              AI智能生成学习计划
            </div>
          }
          open={aiModalVisible}
          onCancel={() => {
            setAiModalVisible(false);
            setAiInputValue('');
          }}
          onOk={handleAiGenerate}
          confirmLoading={aiGenerating}
          width={600}
          okText="生成计划"
          cancelText="取消"
        >
          <div style={{ marginBottom: '16px' }}>
            <Text type="secondary">
              请描述您的学习需求，AI将为您生成个性化的学习计划和任务清单。
            </Text>
          </div>
          
          <TextArea
            value={aiInputValue}
            onChange={(e) => setAiInputValue(e.target.value)}
            placeholder="例如：我想学习Python编程，准备在3个月内掌握基础语法、数据结构、面向对象编程和Web开发..."
            rows={6}
            style={{ marginBottom: '16px' }}
          />
          
          <div style={{ 
            padding: '12px', 
            background: '#f6ffed', 
            border: '1px solid #b7eb8f', 
            borderRadius: '6px',
            fontSize: '13px',
            color: '#52c41a'
          }}>
            <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
              💡 AI将为您生成：
            </div>
            <div>• 个性化的学习计划标题和描述</div>
            <div>• 合理的学习时间安排</div>
            <div>• 3-5个具体的学习任务</div>
          </div>
      </Modal>
    </div>
  );
};

export default StudyPlan;